// src/ChangeProfilePicture.tsx
import React, { type CSSProperties, useRef } from 'react';
import { UserOutlined, CameraOutlined } from '@ant-design/icons';
import { message, Spin } from 'antd';

interface ChangeProfilePictureProps {
  userInfo: {
    id: number;
    username: string;
    nickname: string;
    avatar?: string;
  };
  loading: boolean;
  onUpload: (file: File) => void;
  onUserUpdate?: () => void;
}

const ChangeProfilePicture: React.FC<ChangeProfilePictureProps> = ({
  userInfo,
  loading,
  onUpload
}) => {
  const fileInputRef = useRef<HTMLInputElement>(null);
  const uploadInProgress = useRef(false);

  const styles: { [key: string]: CSSProperties } = {
    avatarSection: {
      display: 'flex',
      flexDirection: 'column',
      alignItems: 'center',
      marginBottom: '20px',
      width: '100%',
    },
    avatarContainer: {
      position: 'relative',
      display: 'flex',
      flexDirection: 'column',
      alignItems: 'center',
      cursor: loading ? 'not-allowed' : 'pointer',
    },
    avatarCircle: {
      width: '80px',
      height: '80px',
      backgroundColor: '#d4a05b',
      borderRadius: '50%',
      display: 'flex',
      flexDirection: 'column',
      alignItems: 'center',
      justifyContent: 'center',
      border: '3px solid #d4a05b',
      marginBottom: '8px',
      transition: 'all 0.3s ease',
      overflow: 'hidden',
      position: 'relative',
    },
    avatarImage: {
      width: '100%',
      height: '100%',
      objectFit: 'cover',
      transition: 'opacity 0.3s ease',
    },
    avatarText: {
      fontSize: '11px',
      color: '#fff',
      textAlign: 'center',
      lineHeight: '1.2',
      marginTop: '4px',
    },
    cameraIcon: {
      position: 'absolute',
      bottom: '4px',
      right: '4px',
      backgroundColor: '#fff',
      borderRadius: '50%',
      padding: '3px',
      boxShadow: '0 2px 4px rgba(0,0,0,0.2)',
      fontSize: '12px',
      zIndex: 2,
    },
    loadingOverlay: {
      position: 'absolute',
      top: 0,
      left: 0,
      right: 0,
      bottom: 0,
      backgroundColor: 'rgba(0,0,0,0.5)',
      borderRadius: '50%',
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
      zIndex: 1,
    }
  };

  const checkAuth = (): boolean => {
    const token = localStorage.getItem('token') || sessionStorage.getItem('token');
    if (!token) {
      message.warning('请先登录');
      setTimeout(() => {
        window.location.href = '/login';
      }, 1000);
      return false;
    }
    return true;
  };

  const handleAvatarUpload = async (event: React.ChangeEvent<HTMLInputElement>) => {
    if (uploadInProgress.current) {
      message.warning('正在上传中，请稍候...');
      return;
    }

    if (!checkAuth()) return;
    
    const file = event.target.files?.[0];
    if (!file) return;

    // 验证文件类型
    if (!file.type.startsWith('image/')) {
      message.error('请选择图片文件 (JPEG, PNG, GIF 等)');
      return;
    }
    
    // 验证文件大小
    if (file.size > 5 * 1024 * 1024) {
      message.error('图片大小不能超过5MB');
      return;
    }

    // 验证图片尺寸
    const img = new Image();
    const objectUrl = URL.createObjectURL(file);
    
    img.onload = () => {
      URL.revokeObjectURL(objectUrl);
      if (img.width > 2000 || img.height > 2000) {
        message.error('图片尺寸过大，建议使用小于 2000x2000 的图片');
        return;
      }
      
      // 开始上传
      uploadInProgress.current = true;
      onUpload(file);
    };
    
    img.onerror = () => {
      URL.revokeObjectURL(objectUrl);
      message.error('图片加载失败，请选择有效的图片文件');
    };
    
    img.src = objectUrl;

    // 重置input，允许选择相同文件再次触发onChange
    if (fileInputRef.current) {
      fileInputRef.current.value = '';
    }
  };

  const handleAvatarClick = () => {
    if (loading || uploadInProgress.current) {
      return;
    }
    fileInputRef.current?.click();
  };

  return (
    <div style={styles.avatarSection}>
      <div style={styles.avatarContainer}>
        <input
          ref={fileInputRef}
          type="file"
          accept="image/jpeg,image/png,image/gif,image/webp"
          style={{ display: 'none' }}
          onChange={handleAvatarUpload}
          disabled={loading || uploadInProgress.current}
        />
        <div 
          style={styles.avatarCircle}
          onClick={handleAvatarClick}
        >
          {userInfo.avatar ? (
            <>
              <img 
                src={userInfo.avatar} 
                alt="用户头像" 
                style={{
                  ...styles.avatarImage,
                  opacity: loading ? 0.7 : 1
                }}
              />
              {loading && (
                <div style={styles.loadingOverlay}>
                  <Spin size="small" style={{ color: '#fff' }} />
                </div>
              )}
            </>
          ) : (
            <>
              <UserOutlined style={{ fontSize: '36px', color: '#fff' }} />
              {loading && (
                <div style={styles.loadingOverlay}>
                  <Spin size="small" style={{ color: '#fff' }} />
                </div>
              )}
            </>
          )}
          <div style={styles.avatarText}>
            {loading ? '上传中...' : '更改头像'}
          </div>
        </div>
        <CameraOutlined style={styles.cameraIcon} />
      </div>
    </div>
  );
};

export default ChangeProfilePicture;